C++ 最小化到托盘
#define WM_SHOWTASK (WM_USER + 1)
void CTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
//增加关闭时最小化到托盘的函数
if (nID == SC_CLOSE) //SC_MINIMIZE
{
ToTray();
return;
}
CDialog::OnSysCommand(nID, lParam);
}
}
BEGIN_MESSAGE_MAP(CTestDlg, CDialog)
ON_MESSAGE(WM_SHOWTASK, OnShowTask)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//在托盘区添加图标 最小化到托盘函数
void ToTray(void);
void CTestDlg::ToTray(void)
{
NOTIFYICONDATA nid;
nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd = this->m_hWnd;
nid.uID = IDR_MAINFRAME;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_SHOWTASK;//自定义的消息名称
nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));
wcscpy_s(nid.szTip, _T("***程序"));//信息提示条
Shell_NotifyIcon(NIM_ADD, &nid);//在托盘区添加图标
ShowWindow(SW_HIDE);//隐藏主窗口
}
//恢复界面函数
afx_msg LRESULT OnShowTask(WPARAM wParam, LPARAM lParam);
//托盘事件
LRESULT CTestDlg::OnShowTask(WPARAM wParam, LPARAM lParam)
{
if (wParam != IDR_MAINFRAME)
{
return 1;
}
switch(lParam)
{
case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个关闭
{
LPPOINT lpoint = new tagPOINT;
::GetCursorPos(lpoint);//得到鼠标位置
CMenu menu;
menu.CreatePopupMenu();//声明一个弹出式菜单
//增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口(已
//隐藏),将程序结束。
menu.AppendMenu(MF_STRING, WM_DESTROY, _T("退出"));
//确定弹出式菜单的位置
menu.TrackPopupMenu(TPM_LEFTALIGN, lpoint->x, lpoint->y, this);
//资源回收
HMENU hmenu = menu.Detach();
menu.DestroyMenu();
delete lpoint;
}
break;
case WM_LBUTTONDBLCLK://双击左键的处理
{
this->ShowWindow(SW_SHOW);//简单的显示主窗口
this->ShowWindow(SW_RESTORE);
DeleteTray();
}
break;
default:
break;
}
return 0;
}
//删除托盘中图标
void DeleteTray();
void CTestlDlg::DeleteTray()
{
NOTIFYICONDATA nid;
nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd = this->m_hWnd;
nid.uID = IDR_MAINFRAME;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_SHOWTASK;//自定义的消息名称
nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));
wcscpy_s(nid.szTip, _T("***程序"));//信息提示条为“按计划任务提醒”
Shell_NotifyIcon(NIM_DELETE, &nid);//在托盘中删除图标
}
//退出程序需时需要DeleteTray();
void CTestDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: 在此处添加消息处理程序代码
DeleteTray();
}
//修改风格使得他不在任务栏显示
int CTestDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: 在此添加您专用的创建代码
//修改风格使得他不在任务栏显示
ModifyStyleEx(WS_EX_APPWINDOW, WS_EX_TOOLWINDOW);
return 0;
}
DeleteTray改为:
void CTestDlg::DeleteTray()
{
NOTIFYICONDATA nid;
nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd = this->m_hWnd;
nid.uID = IDR_MAINFRAME;
nid.uFlags = NIF_ICON /*| NIF_MESSAGE | NIF_TIP*/;
//nid.uCallbackMessage = WM_SHOWTASK;//自定义的消息名称
//nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));
//wcscpy_s(nid.szTip, _T("***程序"));//信息提示条为“按计划任务提醒”
Shell_NotifyIcon(NIM_DELETE, &nid);//在托盘中删除图标
}
否则会出现程序退出后,托盘图标还在的情况,鼠标移动到图标上后,图标一闪然后消失的问题。